package com.qhsx.asset.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.qhsx.asset.domain.*;
import com.qhsx.asset.mapper.*;
import com.qhsx.asset.vo.AssetOutProductVO;
import com.qhsx.asset.vo.SaomaItemVo;
import com.qhsx.common.exception.CustomException;
import com.qhsx.common.utils.DateUtils;
import com.qhsx.common.utils.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qhsx.asset.service.IAssetDeliveryService;

/**
 * 出库管理Service业务层处理
 *
 * @author yepanpan
 * @date 2021-03-05
 */
@Service
public class AssetDeliveryServiceImpl implements IAssetDeliveryService
{
    @Autowired
    private AssetUseMapper assetUseMapper;
    @Autowired
    private AssetPickupMapper assetPickupMapper;
    @Autowired
    private AssetDeliveryMapper assetDeliveryMapper;
    @Autowired
    private AssetInfoMapper assetInfoMapper;
    @Autowired
    private AssetMaterialMapper assetMaterialMapper;

    @Autowired
    private AssetProductMapper assetProductMapper;

    /**
     * 查询出库管理
     *
     * @param id 出库管理ID
     * @return 出库管理
     */
    @Override
    public AssetDelivery selectAssetDeliveryById(Long id)
    {
        return assetDeliveryMapper.selectAssetDeliveryById(id);
    }

    /**
     * 查询出库管理列表
     *
     * @param assetDelivery 出库管理
     * @return 出库管理
     */
    @Override
    public List<AssetDelivery> selectAssetDeliveryList(AssetDelivery assetDelivery)
    {
        return assetDeliveryMapper.selectAssetDeliveryList(assetDelivery);
    }

    @Override
    public  List<SaomaItemVo>  appList(AssetDelivery assetDeliveryDto){
        List<AssetDelivery> assetDeliveryList = selectAssetDeliveryList(assetDeliveryDto);
        List<SaomaItemVo> voList=new ArrayList<>();
        for (AssetDelivery assetDelivery:assetDeliveryList){
            SaomaItemVo saomaItemVo=new SaomaItemVo();
            saomaItemVo.setCreateTime(assetDelivery.getCreateTime());
            saomaItemVo.setName(assetDelivery.getAsset()!=null?assetDelivery.getAsset().getName():assetDelivery.getMaterial().getName());
            voList.add(saomaItemVo);
        }
        return voList;
    }

    /**
     * 新增出库管理
     *
     * @param assetDelivery 出库管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAssetDelivery(AssetDelivery assetDelivery)
    {
        int i = 0;
    	if(assetDelivery.getAssetId() != null) {
    		AssetInfo info = assetInfoMapper.selectAssetInfoById(assetDelivery.getAssetId());
    		if(info == null) {
    			throw new CustomException("资产不存在或者已经被领用");
    		}
    		assetDelivery.setHouseId(info.getHouseId());
    		AssetUse use = assetUseMapper.selectAssetUseById(assetDelivery.getApplyId());
    		if(use == null) {
    			throw new CustomException("没有使用申请信息");
    		}
    		if(!info.getUseUserId().equals(use.getApplyUserId())) {
    			throw new CustomException("申请信息有误");
    		}
    		if("Y".equalsIgnoreCase(use.getIsDelivery())) {
    			throw new CustomException("已经出库的不能重复出库");
    		}else {
    			use.setIsDelivery("Y");
    			assetUseMapper.updateAssetUse(use);
    		}
            ArrayList<Long> longs = new ArrayList<>();
            List<AssetProduct> byMaterialId = assetProductMapper.getByMaterialId(info.getId());
            if (byMaterialId.size() == 1){
                byMaterialId.stream().forEach(item->{
                    longs.add(item.getId());
                });
                assetDelivery.setIds(longs);
            }else {
                throw new CustomException("出库产品异常");
            }

        }
    	if(assetDelivery.getMaterialId() != null) {
            if (assetDelivery.getIds().size() <= 0){
                throw new CustomException("请选择出库产品");
            }
            AssetPickup pickup = assetPickupMapper.selectAssetPickupById(assetDelivery.getApplyId());
            if (assetDelivery.getIds().size() != pickup.getAmount().intValue()){
                throw new CustomException("领用数量与申请数量不一致");
            }
            if(pickup == null) {
                throw new CustomException("没有领用申请信息");
            }
            if("Y".equalsIgnoreCase(pickup.getIsDelivery())) {
                throw new CustomException("已经出库的不能重复出库");
            }else {
                pickup.setIsDelivery("Y");
                assetPickupMapper.updateAssetPickup(pickup);
            }
//    		AssetMaterial material = assetMaterialMapper.selectAssetMaterialById(assetDelivery.getMaterialId());
//    		if(material == null || material.getAmount().floatValue() < assetDelivery.getAmount().floatValue()) {
//    			throw new CustomException("耗材不不存在或者库存不足");
//    		}

            List<AssetProduct> assetProducts = assetProductMapper.selectByIds(assetDelivery.getIds());
            boolean sameCateId = true;
            for (AssetProduct ap : assetProducts) {
                if (ap.getCateId() != pickup.getCateId()) {
                    sameCateId = false;
                }
            }
            if (!sameCateId) {
                throw new CustomException("出库耗材和申请耗材类别不同");
            }
            AssetMaterial material = null;
            for (AssetProduct ap : assetProducts) {
                material = assetMaterialMapper.selectAssetMaterialById(ap.getMaterialId());
                //减库存
                material.setAmount(material.getAmount().subtract(new BigDecimal(1)));
                //更新出库状态
                assetMaterialMapper.updateAssetMaterial(material);
            }
            assetDelivery.setHouseId(material.getHouseId());
        }
        //保存出库记录
        assetDelivery.setCreateTime(DateUtils.getNowDate());
        assetDelivery.setCreateBy(SecurityUtils.getUsername());
        i += assetDeliveryMapper.insertAssetDelivery(assetDelivery);
        //更新出库产品状态
        List<AssetProduct> assetProducts = assetProductMapper.selectByIds(assetDelivery.getIds());
        assetProducts.stream().forEach(item->{
            item.setDeliveryId(assetDelivery.getId());
            item.setUpdateBy(SecurityUtils.getUsername());
            item.setStatus(1);
        });
        i += assetProductMapper.updateBach(assetProducts);
        return i;

    }

    /**
     * 修改出库管理
     *
     * @param assetDelivery 出库管理
     * @return 结果
     */
    @Override
    public int updateAssetDelivery(AssetDelivery assetDelivery)
    {
        assetDelivery.setUpdateTime(DateUtils.getNowDate());
        assetDelivery.setUpdateBy(SecurityUtils.getUsername());
        return assetDeliveryMapper.updateAssetDelivery(assetDelivery);
    }

    /**
     * 批量删除出库管理
     *
     * @param ids 需要删除的出库管理ID
     * @return 结果
     */
    @Override
    public int deleteAssetDeliveryByIds(Long[] ids)
    {
        return assetDeliveryMapper.deleteAssetDeliveryByIds(ids);
    }

    /**
     * 删除出库管理信息
     *
     * @param id 出库管理ID
     * @return 结果
     */
    @Override
    public int deleteAssetDeliveryById(Long id)
    {
        return assetDeliveryMapper.deleteAssetDeliveryById(id);
    }

    @Override
    public List<AssetOutProductVO> selectOutProduct(AssetOutProductVO assetOutProductVO,AssetDelivery assetDelivery) {

        List<AssetOutProductVO> assetOutProductVOS = null;
        if (assetDelivery.getMaterialId() != null && assetDelivery.getAssetId() == null){
            assetOutProductVOS  = assetDeliveryMapper.selectOutProduct(assetOutProductVO.getDeliveryId(), assetOutProductVO.getCateId(), assetOutProductVO.getHandle());
        }
        if (assetDelivery.getMaterialId() == null && assetDelivery.getAssetId() != null){
            assetOutProductVOS = assetDeliveryMapper.selectAssetInfoOutProduct(assetOutProductVO.getDeliveryId(),assetOutProductVO.getCateId(),assetOutProductVO.getHandle());
        }
        return assetOutProductVOS;
    }
}
